#import "FileOpenPlugin.h"
#import "FilePreviewFactory.h"
@implementation FileOpenPlugin 
{
    FlutterResult _result;
    UIViewController *_viewController;
    UIDocumentInteractionController *documentCtr;
}

+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
    
    FilePreviewFactory* factory = [[FilePreviewFactory alloc] initWithMessenger:registrar.messenger];
    [registrar registerViewFactory:factory withId:@"ac/file_preview"];
    

  FlutterMethodChannel* channel = [FlutterMethodChannel
      methodChannelWithName:@"xyx/file_open"
            binaryMessenger:[registrar messenger]];
  FileOpenPlugin* instance = [[FileOpenPlugin alloc] init];
  [registrar addMethodCallDelegate:instance channel:channel];
}


- (instancetype)init{
    self = [super init];
    if (self) {
        _viewController = [UIApplication sharedApplication].delegate.window.rootViewController;
        documentCtr = [[UIDocumentInteractionController alloc] init];
        documentCtr.delegate = self;
    }
    return self;
}

- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
    if ([@"open_file" isEqualToString:call.method]) {
      NSString *path = call.arguments[@"path"];
      [documentCtr setURL:[NSURL fileURLWithPath:path]];
      bool succress = [documentCtr presentOptionsMenuFromRect:CGRectZero inView:_viewController.view animated:YES];
      result([NSNumber numberWithInt:succress?0:-2]);
    } else {
      result(FlutterMethodNotImplemented);
    }
}


#pragma delegate
- (UIViewController*)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController*)controller{
    return _viewController;
}

- (UIView*)documentInteractionControllerViewForPreview:(UIDocumentInteractionController*)controller{
    return _viewController.view;
}

- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController*)controller{
    return _viewController.view.frame;
}

@end
